<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { optionApi as MainApi, optionById as MainById } from '@T2/service/api.ts';
import { useCurrentWatchStore } from '@T2/store/users.ts';
import { deepCopy } from '@T2/utils/utils.ts';

const currentWatchStore = useCurrentWatchStore();
const { curProject } = currentWatchStore;

const { type, row, dftData } = defineProps({
  type: {
    type: String,
    validator(value) {
      return ['新增', '编辑'].includes(value);
    },
    required: true,
  },
  row: {
    type: [Object, null],
    required: true,
  },
  dftData: {
    type: [Object, null],
    required: true,
  },
});
const emits = defineEmits(['closed']);
const showRf = ref(true);

onMounted(() => {
  if (type === '新增') {
    Rt.form = {
      ...(dftData || {}),
    };
  } else if (type === '编辑') {
    const { id, name } = deepCopy(row);
    Rt.form = { id, name };
  }
});

const Rt = reactive({
  form: {},
});
const FormRef = ref(null);

const handleSubmit = async () => {
  const isValid = await FormRef.value.validate(valid => valid);
  if (!isValid) {
    return;
  }
  if (type === '新增') {
    AddMain();
  } else if (type === '编辑') {
    EditMain();
  }
}
const AddMain = () => {
  MainApi({
    method: 'post',
    data: {
      ...Rt.form,
      project: curProject.id,
    }
  }).then(res => {
    ElMessage.success('新增成功');
    handleCancel(true);
  }).catch(res => {
    ElMessage.error('新增失败');
    handleCancel(true);
  });
}
const EditMain = () => {
  MainById({
    method: 'patch',
    id: Rt.form.id,
    data: {
      ...Rt.form,
    }
  }).then(res => {
    ElMessage.success('编辑成功');
    handleCancel(true);
  }).catch(res => {
    ElMessage.error('编辑失败');
    handleCancel(true);
  });
}

const handleCancel = (refresh = false) => {
  emits('closed', refresh);
}
</script>

<template>
  <div>
    <el-dialog v-model="showRf" :title="`${ type }${ Rt.form.parent ? '下级' : '' }分组`" width="400px" @closed="handleCancel()">
      <el-form
        ref="FormRef"
        :model="Rt.form"
        label-width="120px"
      >
        <el-form-item prop="name" label="分组名称：" :rules="[{required: true, message: '不能为空', trigger: 'blur'},]">
          <el-input v-model="Rt.form.name"></el-input>
        </el-form-item>
      </el-form>
    
      <template #footer>
        <div style="flex: auto">
          <el-button @click="showRf = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit()">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>

</style>